<?php
/**
 * Created by PhpStorm.
 * User: zhendong
 * Date: 2017/4/19
 * Time: 9:31
 */
namespace Backend\Model;
use Think\Model;

class AdDeliveryModel extends Model
{

    public function __construct() {
        parent::__construct();
    }

    protected $_validate = [
        array('order_id', 'require', '请选择订单！', 1, 'regex', 3),
        array('ad_name', 'require', '请填写广告名称！', 1, 'regex', 3),
        array('ad_name', '', '已存在的广告名称！', 0, 'unique', 3),
        array('price', 'currency', '请填写合法的金额值！', 1, 'regex', 3),
        array('sale_mode', 'require', '请选择售卖方式！', 1, 'regex', 3),
        array('billing_mode', 'require', '请选择计费方式！', 1, 'regex', 3),
        array('code_id', 'require', '请选择目标代码位！', 1, 'regex', 3),

    ];

    protected function _before_insert(&$data) {
        $data['ctime'] = time();
        $data['user_id'] =$_SESSION['id'];
    }

    /**
     * 获取广告投放信息
     * @param array $where
     * @param string $field
     * @return mixed
     */
    public function get_ad_delivery_info($where = [], $field = '') {
        return $this->where($where)->field($field)->select();
    }

    /**
     * 格式化数据
     * @param $arr1
     * @param $arr2
     * @return array
     */
    public function get_ad_delivery_data_format($arr1, $arr2) {
        if(!is_array($arr1) && !is_array($arr2) && !empty($arr1) && !empty($arr2)) {
            return [];
        }
        $data = [];
        foreach($arr1 as $k => $v) {
            if(array_key_exists($v, $arr2)) {
                $data[$v] = !empty($arr2[$v]) ? $arr2[$v] : '';
                unset($arr2[$v]);
            }
        }
        return [$data, $arr2];
    }

    /**
     * 投放状态 0待确认 1草稿 2删除 3待投放 4投放中 5投放完成状态
     * @param $data
     * @return array
     */
    public function get_delivery_state($data) {
        if(empty($data) && !is_array($data) ) return $data;
        $time = time();
        //判断投放是否添加物料
        if (empty($data[0]['ad_id'])) {
            $data[0]['delivery_state'] = 0; //待确认
        } else {
            //判断投放设定时间 1 连续 2 不连续
            if ($data[1]['delivery_time_set'] == 1) {

                if ($data[1]['end_time_set'] == 1) {        //设定结束时间

                    if ($time < $data['1']['start_time']) {
                        $data[0]['delivery_state'] = '3';   //待投放
                    } else if($time <= $data['1']['end_time'] && $this->checkAmount($data[0]) == 0 && $this->checkAdLimit($data) == 0 ) {
                        $data[0]['delivery_state'] = '4';   //投放中
                    } else {
                        $data[0]['delivery_state'] = '5';   //投放完成
                    }

                } else {    //未设定结束时间
                    if ($time < $data['1']['start_time'])
                        $data[0]['delivery_state'] = '3';   //待投放
                    else if ($this->checkAmount($data[0]) == 0 && $this->checkAdLimit($data) == 0)
                        $data[0]['delivery_state'] = '4'; //投放中
                    else
                        $data[0]['delivery_state'] = '5'; //投放完成
                }

            } else {    //不连续时间段

                if ($this->checkAmount($data[0]) == 0 && $this->checkAdLimit($data) == 0)
                    $data[0]['delivery_state'] = '4'; //投放中
                else
                    $data[0]['delivery_state'] = '5'; //投放完成
            }
        }

        return $data;
    }


    /**
     * 检查订单下广告投放金额是否越界【金额已达到上限】
     * @param array $param
     * @return int
     */
    public function checkAmount($param = []) {
        $orderInfo = M("AdOrder")->where(['id' => $param['order_id']])->field('order_name,amount,total_amount') ->find();
        if ($orderInfo['total_amount'] > $orderInfo['amount']) {
            return 1;   //已越界
        } else {
            return 0;   //无越界
        }
    }


    /**
     * 检查广告投放是否已达到上限设置【展现次数】
     * @param $data
     * @return int
     */
    public function checkAdLimit($data) {
        $count = $this->getReportDataCount('dsp', 'xm_view', ['delivery_id' => $data[0]['id']] );
        if ( !empty($data[1]['delivery_limit']) && ($count > $data[1]['delivery_limit']) ) {
            return 1;   //已达到上限
        } else {
            return 0;   //未达到上限
        }
    }

    /**
     * 获取报告总数据
     * @param string $db
     * @param string $collection
     * @param array $filter
     * @return mixed
     */
    public function getReportDataCount($db = '', $collection = '', $filter = []) {
        $base = A('Base');
        return $base->mongoCount($db, $collection, $filter);
    }

    /**
     * 获取时间数据【操作不连续时间|用于多条数据】 Json -> Array
     * @param array $data
     * @return array
     */
    public function getTimeJsonDateToArrs($data = []) {

        foreach ($data['data'] as $k => $v) {
            $res = [];
            $arrTime = json_decode(htmlspecialchars_decode($v['interval_time']), true);
            foreach ($arrTime as $key => $value) {
                $res[] = $value['date'];
            }
            $data['data'][$k]['interval_time'] = $res;
        }

        return $data;
    }

    /**
     * 获取时间数据【操作不连续时间|用于单条数据】 Json -> Array
     * @param array $data
     * @return array
     */
    public function getTimeJsonDateToArr($data = []) {

        $res = [];
        $arrTime = json_decode(htmlspecialchars_decode($data['interval_time']), true);
        foreach ($arrTime as $key => $value) {
            $res[] = $value['date'];
        }
        $data['interval_time'] = $res;

        return $data;
    }

    /**
     * 获取广告投放关联数据【单条、无分页】
     * @param array $condition
     * @return mixed
     */
    public function get_ad_delivery_join_find($condition = []) {
        $data = $this->alias("d")
            ->field('d.id,d.order_id,d.ad_name as d_ad_name,d.ad_id as d_ad_id,
                d.code_id as d_code_id,d.delivery_state,d.billing_mode,d.price,d.code_id,
                d.ad_id,d.delivery_state,d.ctime,d.sale_mode,d.carrier_type,c.code_name,
                o.order_name,o.amount,o.total_amount,a.ad_name,s.start_time,s.end_time,s.delivery_time_set,
                s.delivery_limit,s.daily_delivery_limit,s.frequency_limit, s.interval_time, 
                s.end_time_set')
            ->join('__AD_ORDER__ AS o ON d.order_id=o.id','LEFT')
            ->join('__CODE__ AS c ON d.code_id = c.id','LEFT')
            ->join('__AD_DELIVERY_SET__ AS s ON d.id = s.delivery_id','LEFT')
            ->join('__AD__ AS a ON d.ad_id = a.id', 'LEFT')
            ->where($condition)->find();

        return $this->getTimeJsonDateToArr($data);
    }

    /**
     * 获取广告投放关联数据【分页】
     * @param array $condition
     * @param int $pageSize
     * @return mixed
     */
    public function get_ad_delivery_join_data($condition = [], $pageSize = 10) {

        //$where = $condition;
        $where = array('d.user_id' =>$_SESSION['id']);
        $count = $this->alias("d")
            ->field('d.id,d.order_id,d.ad_name as d_ad_name,d.delivery_state,
            d.billing_mode,d.price,d.code_id,d.ad_id,d.delivery_state,d.ctime,
            c.code_name,a.ad_name,s.delivery_time_set,s.start_time,s.end_time,
            s.delivery_limit')
            ->join('__AD_ORDER__ AS o ON d.order_id=o.id','LEFT')
            ->join('__CODE__ AS c ON d.code_id = c.id','LEFT')
            ->join('__AD_DELIVERY_SET__ AS s ON d.id = s.delivery_id','LEFT')
            ->join('__AD__ AS a ON d.ad_id = a.id', 'LEFT')
            ->where($where)->count();

        $page = new \Think\Page($count, $pageSize);
        //配置翻页的样式
        $page->setConfig('prev', '上一页');
        $page->setConfig('next', '下一页');
        $data['page'] = $page->show();

        $limit = $page->firstRow.','.$page->listRows;
        $data['data'] = $this->alias("d")
            ->field('d.id,d.order_id,d.ad_name as d_ad_name,d.delivery_state,
            d.billing_mode,d.price,d.code_id,d.ad_id,d.delivery_state,d.ctime,
            c.code_name,o.order_name,o.amount,o.total_amount,a.ad_name,
            s.delivery_time_set,s.start_time,s.end_time,s.interval_time,
            s.delivery_limit,s.end_time_set')
            ->join('__AD_ORDER__ AS o ON d.order_id=o.id','LEFT')
            ->join('__CODE__ AS c ON d.code_id = c.id','LEFT')
            ->join('__AD_DELIVERY_SET__ AS s ON d.id = s.delivery_id','LEFT')
            ->join('__AD__ AS a ON d.ad_id = a.id', 'LEFT')
            ->where($where)->limit($limit)->order('d.id DESC')->select();

        $data = $this->getTimeJsonDateToArrs($data);
        return $this->burningProgress($data);

    }

    /**
     * 投放燃烧进度
     * @param array $data
     * @return array
     */
    public function burningProgress($data = []) {
        $dayTime = time();
        foreach ($data['data'] as $key => $value) {
            if ($value['delivery_time_set'] == 1 && $value['end_time_set'] == 1 && $dayTime >= $value['start_timeround round ']) {

                $burningTime= ( $dayTime - $value['start_time'] ) / 86400 + 1 ;	//投放燃烧时间
                $totalTime  = ( $value['end_time'] - $value['start_time'] ) / 86400 + 1 ;	//投放总时间段

                $data['data'][$key]['schedule'] = ceil(($burningTime / $totalTime * 100));
            } else {
                $data['data'][$key]['schedule'] = 0;
            }

        }

        return $data;
    }
    /**
     * 查询客户投放金额
     */
    public function delivery_consum($pageSize = 10) {


        $where = array(array('a.user_id' =>$_SESSION['id']));
        $count = $this->alias('a')->where($where)->count();
        $page = new \Think\Page($count, $pageSize);
        // 配置翻页的样式
        $page->setConfig('prev', '上一页');
        $page->setConfig('next', '下一页');
        $data['page'] = $page->show();
        /************************************** 取数据 ******************************************/

        $data['data'] = $this->alias('a')
            ->field('a.id,a.ad_name as delivery_name,a.use_amount,sum(b.amount) as amount,sum(b.total_amount) as total_amount ,b.order_name ')
            ->join('dsp_ad_order AS b ON a.order_id= b.id','LEFT')
            ->where($where)
            ->order('a.id desc')
            ->group('a.id')
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
        return $data;
    }
}